package com.qiqi.ctbluetooth

//import cn.wandersnail.bluetooth.BTManager
//import cn.wandersnail.bluetooth.DiscoveryListener
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.provider.Settings
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.TimeUtils
import com.clj.fastble.data.BleDevice
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.engine.base.EngineActivity
import com.drake.engine.utils.EncryptUtil
import com.drake.net.Get
import com.drake.net.utils.scopeDialog
import com.dylanc.longan.doOnClick
import com.dylanc.longan.getCompatColor
import com.dylanc.longan.toast
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.shape.view.ShapeButton
import com.hjq.shape.view.ShapeEditText
import com.hjq.shape.view.ShapeTextView
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.InputDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.qiqi.ctbluetooth.data.BlueDeviceData
import com.qiqi.ctbluetooth.data.TimeData
import com.qiqi.ctbluetooth.databinding.ActivityMainBinding
import com.qiqi.ctbluetooth.databinding.ItemDeviceBinding
import com.qiqi.ctbluetooth.permission.requestBluePermissions
import com.qiqi.ctbluetooth.util.Utils
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json


class MainActivity : EngineActivity<ActivityMainBinding>(R.layout.activity_main){

    companion object{
        const val TAG = "MainActivity"
    }
    val blueViewModel: BlueViewModel by viewModels()


    override fun initData() {
        lifecycleScope.launch {
            blueViewModel.bleDeviceList.collect { devices ->
                binding.rv.models = devices
            }
        }
    }

    var connectDeviceList = mutableListOf<String>()

    override fun initView() {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_BAR).init()
        binding.v = this
        binding.rv.linear()
            .setup {
                addType<BlueDeviceData>(R.layout.item_device)
                onClick(R.id.tvName){
                    setChecked(layoutPosition, !getModel<BlueDeviceData>(layoutPosition).checked)
                }
                onChecked { position, checked, allChecked ->
                    val model = getModel<BlueDeviceData>(position)
                    model.checked = checked
                    model.notifyChange() // 通知UI跟随数据变化
                }
                onBind {
                    val model = getModel<BlueDeviceData>()
                    var tvName = getBinding<ItemDeviceBinding>().tvName
                    if (connectDeviceList.contains(model.device.mac)){
                        getBinding<ItemDeviceBinding>().tvName.setTextColor(getCompatColor(R.color.red));
                    }else{
                        getBinding<ItemDeviceBinding>().tvName.setTextColor(getCompatColor(R.color.white));
                    }
                }
            }.models = mutableListOf<BlueDeviceData>()
        binding.rv.bindingAdapter.singleMode = true

    }

    override fun onClick(v: View) {
        super.onClick(v)
        when(v.id){
            R.id.btnConnect ->{
                var endMiss = (TimeUtils.string2Millis(UserDataLocal.endTime))
                if (endMiss < System.currentTimeMillis()){
                    toast("有效期已过期,请联系供应商")
                    return
                }

                val list = binding.rv.bindingAdapter.models
                    ?.filterIsInstance<BlueDeviceData>()
                    ?.filter { it.checked }
                    ?.map { it.device }
                if (list.isNullOrEmpty()){
                    toast("请选择蓝牙")
                }else{
                    blueViewModel.stopScan()
                    ChartActivity.lunch(list[0])
                }
            }
            R.id.btnScan ->{
                requestBluePermissions { grantedList, deniedList ->
                    toast("开始搜索设备")
                    blueViewModel.startScanBlue()
                }
            }
            R.id.btnOpen ->{
                startActivity(Intent(Settings.ACTION_BLUETOOTH_SETTINGS))
            }
            R.id.btnExchange->{
                CustomDialog.show(object : OnBindView<CustomDialog>(R.layout.dialog_activation){
                    override fun onBind(dialog: CustomDialog, v: View) {
                        var tvDeviceId : ShapeTextView = v.findViewById(R.id.tvDeviceId)
                        var ivCopy : AppCompatImageView = v.findViewById(R.id.ivCopy)
                        var btnActivation : ShapeButton = v.findViewById(R.id.btnActivation)
                        var btnCancel : ShapeButton = v.findViewById(R.id.btnCancel)
                        var edCode : ShapeEditText = v.findViewById(R.id.edCode)
                        tvDeviceId.text = DeviceUtils.getUniqueDeviceId()
                        ivCopy.doOnClick {
                            ClipboardUtils.copyText(tvDeviceId.text.toString())
                            toast("复制成功")
                        }
                        btnActivation.doOnClick {
                            var decryStr = Utils.decryptAES(edCode.text.toString())
                            var device = decryStr.split("##").getOrNull(0)
                            var time = decryStr.split("##").getOrNull(1) ?: ""
                            if (device != DeviceUtils.getUniqueDeviceId()){
                                toast("兑换码错误")
                                edCode.setText("")
                                return@doOnClick
                            }
                            if (!Utils.isValidDateTime(time)){
                                toast("兑换码错误")
                                edCode.setText("")
                                return@doOnClick
                            }
                            UserDataLocal.endTime = time
                            toast("兑换成功,有效期至 $time")
                            LogUtils.i("兑换码正确:设备==》 $device,  时间==》 $time")
                            dialog.dismiss()
                        }
                        btnCancel.doOnClick {
                            dialog.dismiss()
                        }


                    }

                }).setMaskColor(Color.parseColor("#4D000000")).setCancelable(false)

            }
        }
    }




    private fun getDeviceList(): List<BlueDeviceData> {
        return binding.rv.models as List<BlueDeviceData>
    }

    fun isContains(device: BleDevice) : Boolean{
        for (item in getDeviceList()){
            if (item.device.mac == device.mac){
                return true
            }
        }
        return false
    }

    override fun onResume() {
        super.onResume()
        regIsToday()
        connectDeviceList = UserDataLocal.getConnectDeviceList()

        requestBluePermissions { grantedList, deniedList ->
            LogUtils.i("权限申请成功==>:$grantedList")
            blueViewModel.startScanBlue()
        }

    }

    override fun onDestroy() {
        blueViewModel.cleanup()
        super.onDestroy()
    }

    fun regIsToday() = scopeDialog{
        var dataJson = Get<String>(Api.GET_TIME).await()
        try {
            var jsonUtil: Json = Json {
                ignoreUnknownKeys = true  //忽略未知字段
                coerceInputValues = true  //返回的json字段为空或赋值默认值
            }
            val data = jsonUtil.decodeFromString<TimeData>(dataJson)

            if (!TimeUtils.isToday(data.data)){
                MessageDialog.show("提示", "当前系统时间错误，请检查系统时间之后重试", "确定")
                    .setCancelable( false)
                    .setOkButton { dialog, v,  ->
                        finish()
                        false
                    };
            }
        }catch (e:Exception){
            LogUtils.e("regIsToday error:$e")
            MessageDialog.show("提示", e.toString(), "确定")
                .setCancelable( false)
                .setOkButton { dialog, v,  ->
                    finish()
                    false
                };
        }
    }


}